package com.util.taglib;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import com.util.portal.CodeNameEnum;

/**
 * 由枚举类编码获取名称
 * 
 */
public class EnumConversion extends TagSupport {
    /**
     * 枚举类所属命名空间前缀
     */
    public static final String nameSpacePrefix = "com.portal.model.";

    /**
     * 枚举类名
     * 
     * @param className
     */
    public void setClassName(String className) {
        this.className = EnumConversion.nameSpacePrefix + className.replaceAll("\\.", "\\$");
    }

    /**
     * 编码
     */
    public void setCode(String code) {
        this.code = code;
    }

    @SuppressWarnings("unchecked")
    public int doEndTag() throws JspException {
        JspWriter out = pageContext.getOut();

        try {
            // 获取枚举类型
            Class<? extends CodeNameEnum> enumClass = (Class<? extends CodeNameEnum>) Class
                    .forName(this.getClassName());

            // 循环遍历枚举类，并打印出对应的名称
            for (CodeNameEnum e : (CodeNameEnum[]) enumClass
                    .getMethod("values").invoke(null)) {
                if (String.valueOf(e.getCode()).equals(this.getCode())) {
                    out.print(e.getName());
                    break;
                }
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return EVAL_PAGE;
    }

    protected String getClassName() {
        return this.className;
    }

    protected String getCode() {
        return this.code;
    }

    private String className = null;
    private String code = null;
    private static final long serialVersionUID = 1L;
}
